package com.brave.mvvm.mvvmhelper.http;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function4;

/**
 * <b><i>author</i></b> : brave tou
 * <br/>
 * <b><i>time</i></b>   : 2021/9/6 10:52
 * <br/>
 * <b><i>decs</i></b>   : 观察者基类
 */
public abstract class BaseObserver<T> implements Observer<T> {
    private Disposable mDisposable = null;

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        this.mDisposable = d;
    }

    @Override
    public void onNext(T t) {
        if (t instanceof BaseResponse) {
            BaseResponse response = (BaseResponse) t;
            Function4<Integer, String, Function1<? super Throwable, Unit>, Object, Boolean>
                    callback = ExceptionHandle.getInstance().getCallback();
            if (null != callback) {
                // 是否已消费事件
                Boolean isConsume = callback.invoke(response.getCode(), response.getMsg(), throwable -> {
                    onFailure(throwable);
                    return null;
                }, response.getData());
                if (null != isConsume && !isConsume) {
                    onSuccess(t);
                }
            } else {
                onSuccess(t);
            }
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
        onFailure(e);
    }

    @Override
    public void onComplete() {
        if (null != mDisposable) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }

    /**
     * 成功
     */
    public abstract void onSuccess(T data);

    /**
     * 失败
     */
    public abstract void onFailure(@NonNull Throwable e);
}